# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        def getLength(head):
            length = 0
            while head:
                head = head.next
                length+=1
            return length

        def advance(head, k):
            while head and k>0:
                head = head.next
                k-=1
            return head

        def getTail(head):
            if not head:return None
            while head.next: head = head.next
            return head
        if not head: return None
        length = getLength(head)
        k = length-k
        k = k%length
        if k==0:return head
        tail1 = advance(head, k-1)
        if not tail1: return head
        head2 = tail1.next
        if not head2: return head
        tail2 = getTail(head2)
        tail2.next = head
        tail1.next = None
        return head2

head = ListNode(1)
head.next = ListNode(2)

head = Solution().rotateRight(head, 2)